package com.hjx.http.conn;

import com.hjx.http.proxy.ProxyFetchUtil;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.conn.SchemePortResolver;
import org.apache.http.impl.conn.DefaultRoutePlanner;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by houjinxin on 2017/6/20.
 */
public class ProxyBindRoutePlanner extends DefaultRoutePlanner {

    private Logger logger = LoggerFactory.getLogger(ProxyBindRoutePlanner.class);

    public ProxyBindRoutePlanner() {
        this(null);
    }

    public ProxyBindRoutePlanner(SchemePortResolver schemePortResolver) {
        super(schemePortResolver);
    }

    @Override
    protected HttpHost determineProxy(
            final HttpHost target,
            final HttpRequest request,
            final HttpContext context) throws HttpException {

        if(!ProxyFetchUtil.isProxyDisabled()){
            String[] proxyInfo = ProxyFetchUtil.getProxyInfo();
            if (proxyInfo != null && proxyInfo.length == 2) { //未设置代理
                String ip  = proxyInfo[0];
                int port = Integer.valueOf(proxyInfo[1]);
                logger.info("代理设置成功，ip：{}， port：{}", ip, port);
                return new HttpHost(ip, port);
            }
        } else {
            logger.info("URL:{} 本次请求代理未设置", request.getRequestLine().getUri());
        }

        return null;
    }
}
